package student.thread.exception;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用ReentrantLock，同步块异常需要手动释放锁
 * 使用synchronized，异常发生了自动释放锁
 *
 * @author srx
 */
public class ReentrantLockTest {

    public static void main(String[] args) throws InterruptedException {
        final Object o = new Object();
        final Lock lock = new ReentrantLock();
        Runnable r1 = () -> {
            try {
                lock.lock();
                if (true) {
                    throw new RuntimeException("throws");
                }
                lock.unlock();
            } catch (Exception e) {

            }
        };

        Runnable r2 = () -> {
            synchronized (o) {
                try {
                    System.out.println("开始");
                    lock.lock();
                    System.out.println("acquire lock");
                    lock.unlock();
                } catch (Exception e) {

                }
            }
        };

        new Thread(r1).start();
        Thread.sleep(1000);
        new Thread(r2).start();
    }
}